<?php

class RegionMap extends Map implements MapInterface
{  

    const GLOBAL_TOPIC_DEFAULT_VALUE = 0;
    
    const TOPIC_DEFAULT_VALUE = 0;  

    public function __construct($is_wms, $table_gateway, $singleton_registry)
    {
        $this->is_wms_ = $is_wms;
        $this->output_handler_ = $singleton_registry->getSingleton('OutputHandler');
        $this->request_ = $singleton_registry->getSingleton('Request');
        $this->session_ = $singleton_registry->getSingleton('Session');
        $this->language_handler_ = $singleton_registry->getSingleton('LanguageHandler');
        $this->singleton_registry_ = $singleton_registry;
        $this->table_gateway_ = $table_gateway;
    }
        
    public function __destruct(){}
    
    public function init()
    {
        $this->map_ = ms_newMapObj("bezirke.map");
        $arr_maps = $this->table_gateway_->getAvailabeMaps();
        $map_id = key($arr_maps);
        $map_id = $this->request_->issetParameter('get', 'm_id') ? (int)$this->request_->getParameter('get', 'm_id') : $map_id;
        $map_id = $this->request_->issetParameter('post', 'available_layers') ? (int)$this->request_->getParameter('post', 'available_layers') : $map_id;
        $this->session_name_ = "Map_" . $this->map_id_;
        $this->table_details_ = $this->table_gateway_->getDataDetails($map_id);
        if($this->table_details_ === false)
            throw new Exception('Unable to get Map Details');
        $this->map_->setProjection('init=epsg:' . $this->table_details_->e_projection);
        $arr_extent = explode(';', $this->table_details_->e_bbox);
        if(count($arr_extent) != 4)
            throw new Exception('Illegal Bounding Box');
        $this->map_->setExtent($arr_extent[0], $arr_extent[1], $arr_extent[2], $arr_extent[3]);
        $this->output_handler_->assignValuesToTemplate(array("map_projection" => $this->table_details_->e_projection, "arr_map_extent" => $arr_extent, "map_max_resolution" => $this->table_details_->e_resolution, "wms_url" => BASE_URI."index.php?input=regionwms&m_id=".$map_id, "map_url" => BASE_URI."index.php?input=region&amp;m_id=".$map_id, "arr_maps" => $arr_maps, "map_id" => $map_id));
        $this->prepareLayer();
        if($this->is_wms_)
            $this->showWms();
        else
        {
            if($this->request_->issetParameter('get', 'ajax'))
                $this->ajaxRequest();
            else
            {   
                $this->addTopics();
                $this->output_handler_->showTemplate("region");
            }
        }
        return true;
    }
    
    private function ajaxRequest()
    {
        if(!$this->request_->issetParameter('post', 'x') || !$this->request_->issetParameter('post', 'y'))
            return false;
        $arr_checked = $this->checkInput();
        $arr_shapes = array();
        $arr_json = array();
        $arr_data = array();
        $region = $this->table_gateway_->getRegionByCoords($this->table_details_->e_id, $this->request_->getParameter('post', 'x'), $this->request_->getParameter('post', 'y'), $this->table_details_->e_projection);
        if($arr_checked['query_only_layer'])
        {
            if($region !== false)
            {
                $arr_data = $this->table_gateway_->getContainingShapes('shape_'.$this->table_details_->e_id, 'the_geom', $this->request_->getParameter('post', 'x'), $this->request_->getParameter('post', 'y'), $this->table_details_->e_projection);
                $arr_shapes[$this->table_details_->e_id] = $arr_data;
            }
        }
        else
            $arr_shapes = $this->table_gateway_->getGeometryColumns($this->table_details_->e_projection, $this->request_->getParameter('post', 'x'), $this->request_->getParameter('post', 'y'));
        
        if(count($arr_shapes) > 0)
            $arr_data = $this->table_gateway_->getAvailableTables($arr_shapes, $arr_checked);
        $arr_json['meta']['region'] = $region !== false ? $region : $this->language_handler_->getLanguageString('error_unkown_region');
        $arr_json['meta']['results'] = count($arr_data);
        $arr_json['meta']['nodata'] = $this->language_handler_->getLanguageString('error_no_data');
        $arr_json['meta']['language_result'] = $this->language_handler_->getLanguageString('json_result');
        $arr_json['data'] = $arr_data;
        $this->output_handler_->showJSON($arr_json);
    }
    
    private function addTopics()
    {
        
        $topic = new Topic(new TopicGateway());
        $tag = new Tags(new TagsGateway());
        $arr_checked = $this->checkInput();
        $this->session_->set('arr_checked_values', $arr_checked);
        $this->output_handler_->assignValuesToTemplate(array("arr_topics_global" => $tag->getTagCategories(), "arr_topics" => $topic->getTopics(), "arr_checked_values" => $arr_checked));
    }
    
    private function checkInput()
    {
        $arr_checked = array();
        $arr_checked['tg_id'] = $this->request_->issetParameter('post', 'global') ? (int)$this->request_->getParameter('post', 'global') : constant("self::GLOBAL_TOPIC_DEFAULT_VALUE");
        $arr_checked['t_id'] = $this->request_->issetParameter('post', 'topic') ? (int)$this->request_->getParameter('post', 'topic') : constant("self::TOPIC_DEFAULT_VALUE");
        if($this->request_->issetParameter('post', 'topic'))
        {
            $arr_checked['query_only_layer'] = $this->request_->issetParameter('post', 'query_only_layer')? true : false;
            $arr_checked['query_only_verified_topcis'] = $this->request_->issetParameter('post', 'query_only_verified_topcis')? true : false;
        }
        else
        {
            $arr_checked['query_only_layer'] = true;
            $arr_checked['query_only_verified_topcis'] = false;
        }
        return $arr_checked;
    }
    
    private function prepareLayer()
    {
        if($this->is_wms_  || $this->request_->issetParameter('get', 'debug'))
        {
            $this->layer_ = $this->map_->getLayerByName('data_layer');
            $this->layer_->set('classitem', 'gid');
            $this->layer_->set('data', 'the_geom from shape_'.$this->table_details_->e_id);
            $this->layer_->set('labelitem', 'region');
            $class_obj = ms_newClassObj($this->layer_);
            $class_obj->set('name', 'Basis');
            $class_obj->label->outlinecolor->setRGB(255,255,255);
            $class_obj->label->set('minfeaturesize',80);
            $style = ms_newStyleObj($class_obj);
            $style->color->setRGB(224, 174, 32);
            $style->outlinecolor->setRGB(255,255,255);
        }
    }
    
    private function showWms()
    {
        $this->session_->set('js_activated', true);
        $this->map_->setSize((int)$this->request_->getParameter('get', 'WIDTH'), (int)$this->request_->getParameter('get', 'HEIGHT'));
        $arr_extent = explode(',', $this->request_->getParameter('get', 'BBOX'));
        $this->session_->set($this->session_name_.'.width', (int)$this->request_->getParameter('get', 'WIDTH'));
        $this->session_->set($this->session_name_.'.height', (int)$this->request_->getParameter('get', 'HEIGHT'));
        $this->session_->set($this->session_name_.'.bbox', $arr_extent);
        $this->map_->setExtent($arr_extent[0], $arr_extent[1], $arr_extent[2], $arr_extent[3]);
        $this->output_handler_->addHeader("Content-Type", "image/png");
        $this->output_handler_->addHeader("Last-Modified:", date("D, d M Y H:i:s T", time() - 30));
        $this->output_handler_->addHeader("Cache-Control:", "no-store, no-cache, must-revalidate");
        $this->output_handler_->showHeaders();
        $this->createMap()->saveImage('');
    }
}

?>
